// 创建方块的方法

// 创建列
function createCols(cols) {
  return new Array(cols).fill(0)
}

// 创建整个游戏的方块
function createBlocks(rows, cols) {
  return new Array(rows).fill().map(() => createCols(cols)) 
}

// 深拷贝数组，callback对每个数字进行赋值
function deepCopy(blocks, callback) {
  return blocks.map(row => row.map(col => callback ? callback(col): col))
}

// 合并展示
function mergeBlocks(baseBlocks, targetBlocks, offsetRow, offsetCol) {
  for(let row = 0; row < targetBlocks.length; row++) {
    for(let col = 0; col < targetBlocks[row].length; col++) {
      const baseRow = offsetRow + row, baseCol = offsetCol + col;
      if(targetBlocks[row][col]
        && (baseRow >= 0 && baseRow < baseBlocks.length)
        && (baseCol >= 0 && baseCol < baseBlocks[baseRow].length)
        && !baseBlocks[baseRow][baseCol]) {
          baseBlocks[offsetRow + row][offsetCol + col] = targetBlocks[row][col]
      }
    }
  }
  return baseBlocks;
}

// 对角线翻转
function flip(blocks) {
  for(let row = 0; row < blocks.length; row++) {
    for(let col = row; col < blocks[row].length; col++) {
      [blocks[row][col], blocks[col][row]] = [blocks[col][row], blocks[row][col]];
    } 
  }
}

// 上下对调
function swap(blocks) {
  for(let row = 0; row < blocks.length / 2; row++) {
    [blocks[row], blocks[blocks.length - row - 1]] = [blocks[blocks.length - row - 1], blocks[row]]
  }  
}

// 旋转
function rotateBlock(blocks, rotate = -1) {
  for(let i = 0; i < Math.abs(rotate); i++) {
    if(rotate > 0) { // 逆时针旋转90度
      swap(blocks);
      flip(blocks);
    } else { // 顺时针旋转90度
      flip(blocks);
      swap(blocks);
    }
  }
}

export {
  createCols,
  createBlocks,
  deepCopy,
  mergeBlocks,
  flip,
  swap,
  rotateBlock
}
